const Koa = require('koa');
const parser = require('koa-parser');
const cors = require('koa2-cors');
const static = require('koa-static');
const koaBody = require('koa-body');
const path = require('path');
const { Sequelize } = require('sequelize');


//连接数据库
const db = new Sequelize('cnode', 'root', 'qazplm123', {
    host: 'localhost', //数据库地址
    dialect: 'mysql', //指定连接的数据库类型
    pool: {
        max: 5, //连接池最大连接数量
        min: 0, //最小连接数量
        idle: 10000, //如果一个线程 10秒内么有被使用过的话，就释放
    },
})
db.authenticate().then(() => {
    console.log('连接数据库成功');
}).catch(err => {
    console.log('连接数据库失败' + err);
});


//挂载方法到Koa
Koa.prototype.Middleware = require('../typings/src/middlewares/index');
Koa.prototype.Service = require('../typings/src/services/index')(db);
Koa.prototype.Controller = require('../typings/src//controllers/index');



const app = new Koa();

//表关联
app.Service.Article.hasMany(app.Service.Replie, {   //一对多，文章对评论
    foreignKey: 'article_id'
})
app.Service.Replie.belongsTo(app.Service.User, {    //一对一，评论对文章
    foreignKey: 'user_id'
})
app.Service.Article.belongsTo(app.Service.Categorie, {  //一对一，文章对分类
    foreignKey: 'category_id'
})
app.Service.Article.belongsTo(app.Service.User, {   //一对一，文章对用户
    foreignKey: 'user_id'
})
app.Service.Article.hasMany(app.Service.Article_content, {  //一对多，文章对内容
    foreignKey: 'article_id'
})
app.Service.Categorie.hasMany(app.Service.Article, {    //一对多，类型对文章
    foreignKey: 'category_id'
})
app.Service.User.hasMany(app.Service.Article, {    //一对多，用户对文章
    foreignKey: 'user_id'
})
app.Service.User.hasMany(app.Service.Replie, {    //一对多，用户对评论
    foreignKey: 'user_id'
})
app.Service.Replie.belongsTo(app.Service.Article, {   //一对一，文章对用户
    foreignKey: 'article_id'
})


//初始化数据库

// app.Service.User.sync({ force: true });
// app.Service.Article_content.sync({ force: true });
// app.Service.Article.sync({ force: true });
// app.Service.Categorie.sync({ force: true });
// app.Service.Replie.sync({ alter: true })
// await sequelize.sync({ force: true });

app.use(koaBody({ multipart: true }));
app.use(parser());
app.use(cors());
app.use(static(path.join(__dirname , '../public')));
console.log(path.join(__dirname , '../public'));

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//路由引用
const router = require('./routes/index');
app.use(router.routes());

//监听3000端口
app.listen(7003, async (ctx) => {
    console.log('成功', 7003);
});

// const process = require("child_process");

// // 执行 npm run build 命令
// (function() {
//   process.exec('start cmd /k "cd C:/Users25617/Desktop/桌面/CNode/CNode/vue-cnode&&npm run serve"', (error, stdout, stderr) => {
//     if (!error) {
//       console.log('成功');
//     } else {
//       console.log(error);
//     }
//   });
// })();



// const User = new (require('./controllers/user'));
// User.getUser();
// module.exports = { db }